package com.goktech.olala.client.controller.customer;

import com.goktech.olala.client.controller.basic.BasicController;
import com.goktech.olala.core.config.SysConfig;
import com.goktech.olala.core.req.ReqCollect;
import com.goktech.olala.core.req.ReqCtmInfo;
import com.goktech.olala.core.req.ReqCtmLogin;
import com.goktech.olala.core.resp.*;
import com.goktech.olala.core.service.ICollectService;
import com.goktech.olala.core.service.ICommentService;
import com.goktech.olala.core.service.ICtmInfoService;
import com.goktech.olala.core.service.IOrderDetailService;
import com.goktech.olala.server.pojo.comment.Comment;
import com.goktech.olala.server.pojo.customer.*;
import com.goktech.olala.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/cntApi")
public class AccountController extends BasicController {
    @Autowired
    ICtmInfoService iCtmInfoService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    ICommentService iCommentService;

    @Autowired
    ICollectService collectService;

    /**
     * 前台登录
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login.do",method = RequestMethod.POST)
    @ResponseBody
    public String login(String userName, String password,
                        HttpServletRequest request, HttpServletResponse response){
        String msg="";
        try {
            String md5Pwd = MD5Util.md5(password);
            RespCtmLogin respCtmLogin = iCtmInfoService.queryCmtInfoForLogin(userName, md5Pwd);
            if(respCtmLogin == null){
                msg = SysConfig.ERROR_CODE_STR;//失败
            }else{
                String customerName = respCtmLogin.getCustomerName();
                String userId = respCtmLogin.getCustomerId();
                //登录信息放置session中
                request.getSession().setAttribute("LoginUserId", userId);
                request.getSession().setAttribute("LoginUserName", customerName);

                //保存登录日志
                ReqCtmLogin reqCtmLogin = new ReqCtmLogin();
                reqCtmLogin.setCustomerId(userId);
                reqCtmLogin.setLoginIp(request.getRemoteAddr());
                reqCtmLogin.setLoginType(1);
                iCtmInfoService.saveLoginLog(reqCtmLogin);

                msg = SysConfig.SUCCESS_CODE_STR;//成功
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return msg;
        }
    }


    /**
     * 前台注册(邮箱注册）
     *
     * @param request
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/register.do",method = RequestMethod.POST)
    @ResponseBody
    public String register(String mobile, String email, String password, String verificationCode,
                  HttpServletRequest request, HttpServletResponse response) throws Exception {
        String msg = "";
        RespCtmLogin userLoginVo = null;
        try {
            RespCtmInfo respCtmInfo = iCtmInfoService.checkUser(mobile, email);
            if(respCtmInfo == null){
                msg = "2";//允许注册
                ReqCtmInfo reqCtmInfo = new ReqCtmInfo();
                reqCtmInfo.setCustomerName(StringUtils.isBlank(mobile)?email:mobile);
                reqCtmInfo.setPassword(password);
                reqCtmInfo.setEmail(email);
                reqCtmInfo.setUserMobile(mobile);
                reqCtmInfo.setGender(SysConfig.DEFAULT_GENDER);
                reqCtmInfo.setIdentyCardType(SysConfig.DEFAULT_IDENTITY_CARD_TYPE);
                reqCtmInfo.setIdentyCardNo(SysConfig.DEFAULT_IDENTITY_CARD_NO);
                userLoginVo = iCtmInfoService.saveCmtInfo(reqCtmInfo);
                if(userLoginVo != null){
                    //登录信息放置session中
                    request.getSession().setAttribute("LoginUserId", userLoginVo.getCustomerId());
                    request.getSession().setAttribute("LoginUserName", userLoginVo.getCustomerName());
                }
            }else {
                msg = "1";
                return msg;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("userLogin", userLoginVo);
        return msg;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/loginOut.do",method = RequestMethod.POST)
    @ResponseBody
    public String loginOut(HttpServletRequest request){
        String msg = "";
        try {
                request.getSession().removeAttribute("LoginUserName");
                request.getSession().removeAttribute("LoginUserId");
                msg = "10000";
            }
        catch (Exception e) {
            e.printStackTrace();
        }
        return msg;

    }

    /*个人信息*/
    @RequestMapping(value = "/info.do")
    @ResponseBody
    public ModelAndView queryInfo(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        if (LoginUserId==null){
            view.setViewName("home/login");
            return view;
        }
        CtmInfo userInfo = iCtmInfoService.queryCustomerIdById(LoginUserId);
        /*对前端页面日期格式进行拆分*/
        String birthday = userInfo.getBirthday();//生日
        if(StringUtils.isNotBlank(birthday)){
            Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
            SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
            SimpleDateFormat sdf1 = new SimpleDateFormat("M");
            SimpleDateFormat sdf2 = new SimpleDateFormat("d");
            String year = sdf0.format(d1);
            String month = sdf1.format(d1);
            String day = sdf2.format(d1);

            view.addObject("birthdayOfYear",year);
            view.addObject("birthdayOfMonth",month);
            view.addObject("birthdayOfDay",day);
        }

        /*年月日存放在不同域中*/
        view.addObject("LoginUserInfo",userInfo);
        request.getSession().setAttribute("SessionLoginUserInfo",userInfo);
        view.setViewName("person/information");
        return view;
    }

    /**
     *  会员地址查询By用户ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/consignee.do")
    @ResponseBody
    public ModelAndView queryConsignee(CtmConsignee ctmConsignee,HttpServletRequest request)
            throws Exception {
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
       if (LoginUserId==null){
            view.setViewName("home/login");
            return view;
        }
        List<RespConsigneeVo> list = iCtmInfoService.queryCustomerConsignee(LoginUserId);
        view.addObject("consignee",list);
        view.setViewName("person/address");
        return view;
    }
    /**
     *  会员地址查询By地址编号
     */
    @RequestMapping(value = "/consigneeByAdd.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView queryConsigneeByAddId(Integer addressId) throws Exception {
        ModelAndView view = new ModelAndView();
        List<CtmConsignee> AddList = iCtmInfoService.queryConsigneeByAddressId(addressId);
        view.addObject("consigneeByAddressId",AddList);
        view.setViewName("person/address");
        return view;
    }

    /**
     * 安全设置
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/safeReset.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView safeReset() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/safety");
        return view;
    }

    /**
     * 快捷支付
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cardBankReset.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView cardBankReset() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/cardlist");
        return view;
    }

    /**
     * 订单管理
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderManager.do")
    @ResponseBody
    public ModelAndView orderManager(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        List<RespOrderDetailVo> respOrderDetailVoList = iOrderDetailService.queryDetailAndMasterOrderById(LoginUserId);
        view.addObject("orderManager",respOrderDetailVoList);
        view.setViewName("person/order");
        return view;
    }

    /**
     * 退款售后
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/refundAfterSale.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView refundAfterSale() throws Exception {
        ModelAndView view = new ModelAndView();

        view.setViewName("person/change");
        return view;
    }

    /**
     * 评价商品
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/commentGoods.do")
    @ResponseBody
    public ModelAndView commentGoods(HttpServletRequest request){
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        List<Comment> comments = null;
        try {
            comments = iCommentService.SelectDetailAndCommentById(LoginUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        view.addObject("comments",comments);
        view.setViewName("person/comment");
        return view;
    }

    /**
     * 优惠券
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myCoupon.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView myCoupon() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/coupon");
        return view;
    }

    /**
     * 红包
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myBonus.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView myBonus() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/bonus");
        return view;
    }

    /**
     * 账单明细
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myBill.do")
    @ResponseBody
    public ModelAndView myBill(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        List<RespOrderDetailVo> respOrderDetailVos = iOrderDetailService.queryDetailAndMasterOrderById(LoginUserId);
        view.addObject("BillDetails",respOrderDetailVos);
        view.setViewName("person/bill");
        return view;
    }


    /**
     * 收藏
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myCollection.do")
    @ResponseBody
    public ModelAndView myCollection(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView view = new ModelAndView();
        ReqCollect reqCollect = new ReqCollect();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        reqCollect.setCustomerId(LoginUserId);
        reqCollect.setIsCancel(1);
        List<RespCollectVo> respCollectVoList = collectService.queryAllMyCollect(reqCollect);
        view.addObject("collectVos", respCollectVoList);
        view.setViewName("person/collection");
        return view;
    }

    /**
     * 足迹
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myLookRecord.do")
    @ResponseBody
    public ModelAndView myLookRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView view = new ModelAndView();
        ReqCollect reqCollect = new ReqCollect();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        reqCollect.setCustomerId(LoginUserId);
        List<RespCollectVo> respCollectVoList = collectService.queryAllMyCollect(reqCollect);
        view.addObject("collectVos", respCollectVoList);
        view.setViewName("person/foot");
        return view;
    }

    /**
     * 商品咨询
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/consultation.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView consultation() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/consultation");
        return view;
    }

    /**
     * 意见反馈
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/suggest.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView suggest() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/suggest");
        return view;
    }

    /**
     * 我的消息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/message.do",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView message() throws Exception {
        ModelAndView view = new ModelAndView();
        view.setViewName("person/news");
        return view;
    }

    /*会员信息更新*/
    @RequestMapping(value = "/updateUserInfo.do",method = RequestMethod.POST)
    @ResponseBody
    public void updateCustomer(HttpServletRequest request,HttpServletResponse response, CtmInfo user) throws Exception {
        ModelAndView view = new ModelAndView();
        /*前端值*/
        Integer radio10 = Integer.parseInt(request.getParameter("radio10"));
        CtmInfo info= (CtmInfo)request.getSession().getAttribute("SessionLoginUserInfo");
        info.setCustomerName(request.getParameter("ctm_name"));
        info.setRealName(request.getParameter("r_name"));
        info.setGender(radio10);

        String year = request.getParameter("year");
        String month =  request.getParameter("month");
        String day = request.getParameter("day");

        if(StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month) && StringUtils.isNotBlank(day)){
            String birthday = year+"-"+month+"-"+day;
            info.setBirthday(birthday);
        }

        info.setUserMobile(request.getParameter("user-phone"));
        info.setEmail(request.getParameter("user-email"));
        /*修改时间*/
        Timestamp createTime = new Timestamp(new Date().getTime());
        info.setModifiedTime(createTime);
        iCtmInfoService.updateCustomerInfoByCtmId(info);
        /*iCtmInfoService.updateCustomerInfo(info);*/
        response.sendRedirect("/olalashop/cntApi/info.do");

    }

    /*新增用户地址*/
    @RequestMapping(value = "/addConsignee.do",method = RequestMethod.POST)
    @ResponseBody
    public String addConsignee(CtmConsignee ctmConsignees, HttpServletRequest request,String user_name,
                             String user_phone,String sheng,String shi,String qu,String user_intro)
            throws Exception {

        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String info = (String)request.getSession().getAttribute("LoginUserId");
        ctmConsignees.setCustomerId(info);
        ctmConsignees.setCustomerUserName(user_name);
        ctmConsignees.setCustomerUserPhone(user_phone);
        ctmConsignees.setZip("000000");
        ctmConsignees.setProvince(sheng);
        ctmConsignees.setCity(shi);
        ctmConsignees.setDistrict(qu);
        ctmConsignees.setAddress(user_intro);
        ctmConsignees.setIsDefault(0);
        ctmConsignees.setModifiedTime(Timestamp.valueOf(nowTime));
        ctmConsignees.setBackUp("");
        iCtmInfoService.addConsignee(ctmConsignees);
        return info;
    }

    /*删除会员地址*/
    @RequestMapping(value = "/delConsignee.do",method = RequestMethod.POST)
    @ResponseBody
    public String delConsignee(Integer user_addId)
            throws Exception {
        if (user_addId != null){
            iCtmInfoService.delConsignee(user_addId);
            return "1";
        }else {
            return "0";
        }
    }

    /*用户积分查询*/
    @RequestMapping(value = "/points.do")
    @ResponseBody
    public ModelAndView queryCustomerPoints(HttpServletRequest request) throws Exception {
        ModelAndView view = new ModelAndView();
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        List<CtmPointLog> ctmPointLogs = null;
        /*String UsablePoints = iCtmInfoService.queryCustomerPointsUsable(LoginUserId);*/
        try {
            ctmPointLogs = iCtmInfoService.queryCustomerPoints(LoginUserId);
        }catch (Exception e) {
            e.printStackTrace();
        }
      /*  view.addObject("UsablePoints",UsablePoints);*/
        view.addObject("point",ctmPointLogs);
        view.setViewName("person/points");
        return view;
    }

    /*签到*/
    @RequestMapping(value = "/addPoint.do",method = RequestMethod.POST)
    @ResponseBody
    public String AddCustomerPoints(HttpServletRequest request,CtmSingLog ctmSingLog,CtmPointLog ctmPointLog) throws Exception {
        String LoginUserId = (String) request.getSession().getAttribute("LoginUserId");
        CtmSingLog time = iCtmInfoService.SelectTimeByID(LoginUserId);
        String msg = "";
        long day = 0;
        /*是否有签到信息 没有就新增*/
        if (time == null) {
            ctmSingLog.setCustomerId(LoginUserId);
            ctmSingLog.setCreateTime(new Date());
            ctmSingLog.setContinueSign(1);
            ctmSingLog.setCount(1);
            ctmSingLog.setUpdateTime(new Date());
            iCtmInfoService.insertSignInfo(ctmSingLog);
            ctmPointLog.setCustomerId(LoginUserId);
            ctmPointLog.setSource(true);
            ctmPointLog.setChargePoint(5);
            ctmPointLog.setCreateTime(new Date());
            ctmPointLog.setChangeDesc("签到积分");
            iCtmInfoService.insertPoint(ctmPointLog);
            msg = "10000";
        } else {
            /*有签到信息 查询当天是否签到过*/
            day = (new Date().getTime() - time.getUpdateTime().getTime()) / (24 * 60 * 60 * 1000);
            CtmSingLog SignInfo = iCtmInfoService.querySignInfoById(LoginUserId);
            /*签到日期相隔1天则为连续签到*/
            if (day>0 && day < 2) {
                SignInfo.setUpdateTime(new Date());
                int i = SignInfo.getCount() + 1;
                SignInfo.setCount(i);
                int j = SignInfo.getContinueSign() + 1;
                SignInfo.setContinueSign(j);
                iCtmInfoService.updateSignInfo(SignInfo);
                ctmPointLog.setCustomerId(LoginUserId);
                ctmPointLog.setSource(true);
                ctmPointLog.setChargePoint(5);
                ctmPointLog.setCreateTime(new Date());
                ctmPointLog.setChangeDesc("签到积分");
                iCtmInfoService.insertPoint(ctmPointLog);
                msg = "10001";
            }
            /*签到日期大于一天则为断签，连续签到变为连续签到1天*/
            else if (day>=2){
                SignInfo.setUpdateTime(new Date());
                int i = SignInfo.getCount() + 1;
                SignInfo.setCount(i);
                SignInfo.setContinueSign(1);
                iCtmInfoService.updateSignInfo(SignInfo);
                ctmPointLog.setCustomerId(LoginUserId);
                ctmPointLog.setSource(true);
                ctmPointLog.setChargePoint(5);
                ctmPointLog.setCreateTime(new Date());
                ctmPointLog.setChangeDesc("签到积分");
                iCtmInfoService.insertPoint(ctmPointLog);
                msg = "10002";
            }
            /*当天签过了*/
            else {
                msg = "10003";
            }

        }
        return msg;
    }





/*账户余额*/

    @RequestMapping(value = "/balance.do")
    @ResponseBody
    public ModelAndView queryBalance(HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        /*PageNavigate pageNavigate = new PageNavigate();*/
        String LoginUserId = (String)request.getSession().getAttribute("LoginUserId");
        if (LoginUserId==null){
            view.setViewName("home/login");
            return view;
        }
        List<CtmBalance> ctmBalance = null;
        try {
            ctmBalance = iCtmInfoService.queryBalance(LoginUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        view.addObject("balance",ctmBalance);
        view.setViewName("person/walletlist");
        return view;
    }



}
